import 'dart:convert';
import 'dart:io';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http/io_client.dart';
import 'package:http/retry.dart';
import 'package:http/src/client.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/plugins/pigeon_api_implementation.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../styles/custom_animation.dart';

/// @Author lixiaobin
/// @Date 2023/11/2
/// @Description
class App {
  App._();

  static App get instance => _getInstance();
  static App? _instance;

  UserInfo? userInfo;
  PackageInfo? packageInfo;
  ServiceInfo? serviceInfo;
  DeviceInfo? deviceInfo;
  AppOtherInfo? appOtherInfo;
  String? envName;
  static bool isDebug = true;
  static bool hasPigeons = false;
  final eventBus = EventBus();
  late RetryClient client;

  ///看门狗url
  String? baseUrl;

  ///云信appKey
  String? imAppKey;

  ///领医h5url
  String? baseH5Url;

  ///健康领克h5url
  String? k8H5Url;

  static App _getInstance() {
    _instance ??= App._();
    return _instance!;
  }

  init() async {
    isDebug = kDebugMode;
    // 初始化环境配置文件
    await dotenv.load(fileName: "config.env");
    // 屏幕适配
    await ScreenUtil.ensureScreenSize();
    // 配置网络请求
    _initClient();
    try {
      // 初始化交互插件
      await _initNativeInterface();
      hasPigeons = true;
    } catch (e) {
      hasPigeons = false;
      Log.i(e);
      _loadTestData();
    }
    await _initEnv();
    FlutterInterface.setup(PigeonApiImplementation());
  }

  /// 初始化网络请求配置 超时15s 重试3次
  _initClient() {
    var httpClient = HttpClient()
      ..idleTimeout = const Duration(seconds: 15)
      ..connectionTimeout = const Duration(seconds: 15);
    client = RetryClient(IOClient(httpClient), retries: 3);
  }

  /// 获取宿主程序数据
  _initNativeInterface() async {
    envName = await NativeInterface().getEnv();
    userInfo = await NativeInterface().getUserInfo();
    packageInfo = await NativeInterface().getPackageInfo();
    serviceInfo = await NativeInterface().getServiceInfo();
    deviceInfo = await NativeInterface().getDeviceInfo();
    appOtherInfo = await NativeInterface().getAppOtherInfo();
  }

  /// 环境变量配置
  _initEnv() async {
    baseUrl = dotenv.env['${envName}_HOST'] ?? '';
    imAppKey = dotenv.env['${envName}_IM_APP_KEY'] ?? '';
    baseH5Url = dotenv.env['${envName}_LY_H5'] ?? '';
    k8H5Url = dotenv.env['${envName}_K8_H5'] ?? '';
  }

  /// 配置loading
  void configLoading() {
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 5000)
      ..indicatorType = EasyLoadingIndicatorType.fadingCircle
      ..loadingStyle = EasyLoadingStyle.dark
      ..indicatorSize = 45.0
      ..radius = 10.0
      ..maskColor = Colors.blue.withOpacity(0.5)
      ..userInteractions = false
      ..dismissOnTap = false
      ..customAnimation = CustomAnimation();
  }

  Widget configRefresh(Widget widget) {
    // 全局配置子树下的SmartRefresher,下面列举几个特别重要的属性
    return RefreshConfiguration(
        headerBuilder: () => const WaterDropHeader(),
        // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
        footerBuilder: () => const ClassicFooter(),
        // 配置默认底部指示器
        headerTriggerDistance: 80.0,
        // 头部触发刷新的越界距离
        springDescription: const SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
        // 自定义回弹动画,三个属性值意义请查询flutter api
        maxOverScrollExtent: 100,
        //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
        maxUnderScrollExtent: 0,
        // 底部最大可以拖动的范围
        enableScrollWhenRefreshCompleted: true,
        //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
        enableLoadingWhenFailed: true,
        //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
        hideFooterWhenNotFull: false,
        // Viewport不满一屏时,禁用上拉加载更多功能
        enableBallisticLoad: true,
        // 可以通过惯性滑动触发加载更多
        child: widget);
  }

  /// 加载测试数据
  _loadTestData() async {
    envName = dotenv.env['ENV_NAME'] ?? '';
    if (isDebug) {
      var env2 = DotEnv();
      await env2.load(fileName: 'test_data.env');
      var user = jsonDecode(env2.env['USER_INFO'] ?? '');
      var service = jsonDecode(env2.env['SERVICE_INFO'] ?? '');
      var package = jsonDecode(env2.env['PACKAGE_INFO'] ?? '');
      var devices = jsonDecode(env2.env['DEVICE_INFO'] ?? '');
      var appLen = jsonDecode(env2.env['APP_OTHER_INFO'] ?? '');
      userInfo = UserInfo(
          id: user['id'], phone: user['phone'], realName: user['realName'], email: user['email']);
      serviceInfo = ServiceInfo(
          phone: service['phone'], email: service['email'], workingTime: service['workingTime']);
      packageInfo = PackageInfo(
          appPackageName: package['appPackageName'],
          appVersionCode: package['appVersionCode'],
          appVersionName: package['appVersionName']);
      deviceInfo = DeviceInfo(
          systemVersion: devices['systemVersion'],
          deviceModel: devices['deviceModel'],
          nickname: devices['nickname'],
          brand: devices['brand']);
      appOtherInfo = AppOtherInfo(cacheLength: appLen['cacheLength']);
    }
  }
}
